﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iDMS.Models;
using System.IO;
using System.Runtime.InteropServices;

namespace iDMS
{
    public static class FileUploadHelper
    {


        [DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
        static extern int FindMimeFromData(IntPtr pBC,
     [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
     [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer,
     int cbSize,
     [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,
     int dwMimeFlags, out IntPtr ppwzMimeOut, int dwReserved);

        public static string getMimeFromFile(HttpPostedFileBase file)
        {
            IntPtr mimeout;

            int MaxContent = (int)file.ContentLength;
            if (MaxContent > 4096) MaxContent = 4096;

            byte[] buf = new byte[MaxContent];
            file.InputStream.Read(buf, 0, MaxContent);
            file.InputStream.Position = 0;
            int result = FindMimeFromData(IntPtr.Zero, file.FileName, buf, MaxContent, null, 0, out mimeout, 0);

            if (result != 0)
            {
                Marshal.FreeCoTaskMem(mimeout);
                return "";
            }

            string mime = Marshal.PtrToStringUni(mimeout);
            Marshal.FreeCoTaskMem(mimeout);

            return mime.ToLower();
        }
        public static int SaveStream2DB(Stream inputStream, string fileExt, string contentType)
        {
            DMSRepository db = new DMSRepository();
            //create byte array of size equal to file input stream
            byte[] fileData = new byte[inputStream.Length];
            //add file input stream into byte array
            inputStream.Read(fileData, 0, Convert.ToInt32(inputStream.Length));
            //create system.data.linq object using byte array
            System.Data.Linq.Binary binaryFile = new System.Data.Linq.Binary(fileData);
            //initialise object of FileDump LINQ to sql class passing values to be inserted
            Resource resource = new Resource() /*{ FileData = binaryFile, FileName = System.IO.Path.GetFileName(Request.Files[upload].FileName) }*/;
            resource.FileExtension = fileExt;
            resource.FileData = binaryFile;
            resource.ContentType = contentType; 

            //call InsertOnsubmit method to pass new object to entity
            db.ResourceAdd(resource);
            db.CommitChanges();
            return resource.ResourceID;
        }

        public static SaveImageResult SaveFile(int maxSize, string allowedExtensions, HttpPostedFileBase file, HttpServerUtilityBase server)
        {
            var result = new SaveImageResult { Success = false };
            if (file == null || file.ContentLength == 0)
            {
                result.Errors.Add("There was problem with sending file.");
                return result;
            }

            // Check image size
            if (file.ContentLength > maxSize)
                result.Errors.Add("File is too big.");

            var extension = Path.GetExtension(file.FileName).Substring(1).ToLower();
            if (allowedExtensions != "")
            {
                // Check image extension                
                if (!allowedExtensions.Contains(extension))
                    result.Errors.Add(string.Format("'{0}' format is not allowed.", extension));
            }

            // If there are no errors save image
            if (!result.Errors.Any())
            {
                //// Generate unique name for safety reasons
                //var newName = Guid.NewGuid().ToString("N") + "." + extension;
                //var serverPath = server.MapPath("~" + path + newName);
                //image.SaveAs(serverPath);

                try
                {
                    result.ResouceID = SaveStream2DB(file.InputStream, extension, getMimeFromFile(file));
                    //result.ResouceID = SaveStream2DB(file.InputStream, extension, file.ContentType);
                    result.Success = true;
                }
                catch
                {
                    result.Errors.Add("DB Error");
                    result.Success = false;
                }
            }
            return result;
        }
    }

    public class SaveImageResult
    {
        public bool Success { get; set; }
        public List<string> Errors { get; set; }
        public int ResouceID { get; set; }
        public SaveImageResult()
        {
            Errors = new List<string>();
        }
    }
}